
package com.jf.cloud.order.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.jf.cloud.api.delivery.dto.ChangeOrderAddrDTO;
import com.jf.cloud.api.delivery.dto.DeliveryOrderDTO;
import com.jf.cloud.api.delivery.dto.DeliveryOrderItemDTO;
import com.jf.cloud.api.delivery.feign.DeliveryFeignClient;
import com.jf.cloud.api.feign.EsOrderFeignClient;
import com.jf.cloud.api.multishop.feign.ShopWalletFeignClient;
import com.jf.cloud.api.order.constant.OrderStatus;
import com.jf.cloud.api.product.feign.ProductFeignClient;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.order.constant.ReturnProcessStatusEnum;
import com.jf.cloud.common.order.vo.OrderAddrVO;
import com.jf.cloud.api.product.feign.SkuFeignClient;
import com.jf.cloud.api.supplier.bo.SupplierDetailBO;
import com.jf.cloud.api.supplier.feign.SupplierDetailFeignClient;
import com.jf.cloud.api.supplier.vo.SupplierApiDetailVO;
import com.jf.cloud.api.user.feign.UserFeignClient;
import com.jf.cloud.api.user.vo.UserApiVO;
import com.jf.cloud.api.vo.EsPageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.order.constant.DeliveryType;
import com.jf.cloud.common.order.constant.OrderActivityType;
import com.jf.cloud.common.order.dto.OrderSearchDTO;
import com.jf.cloud.common.order.vo.*;
import com.jf.cloud.common.product.constant.PreSaleType;
import com.jf.cloud.common.product.constant.SupplierDeliveryType;
import com.jf.cloud.common.product.vo.SkuAddrVO;
import com.jf.cloud.common.product.vo.SpuVO;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.ExcelUtil;
import com.jf.cloud.order.constant.Constant;
import com.jf.cloud.order.constant.RefundStatusEnum;
import com.jf.cloud.order.dto.OrderAddrDTO;
import com.jf.cloud.order.dto.multishop.OrderAdminDTO;
import com.jf.cloud.order.dto.multishop.OrderChangeAddrDTO;
import com.jf.cloud.order.listener.OrderExcelListener;
import com.jf.cloud.order.model.Order;
import com.jf.cloud.order.model.OrderAddr;
import com.jf.cloud.order.model.OrderItem;
import com.jf.cloud.order.service.*;
import com.jf.cloud.order.vo.OrderExcelVO;
import com.jf.cloud.common.order.vo.OrderPreSaleInfoVO;
import com.jf.cloud.common.order.vo.OrderVO;
import com.jf.cloud.order.vo.OrderRefundVO;
import com.jf.cloud.order.vo.UnDeliveryOrderExcelVO;
import io.swagger.v3.oas.annotations.Operation;
import ma.glasnost.orika.MapperFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zz on 2018/09/15.
 */
@RestController("adminOrderController")
@RequestMapping("/mp/order")
public class OrderController {

    @Value("${jfcloud.expose.operation.auth:}")
    private Boolean permission;

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private ShopWalletFeignClient shopWalletFeignClient;
    @Autowired
    private OrderPreSaleInfoService orderPreSaleInfoService;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private SupplierDetailFeignClient supplierDetailFeignClient;
    @Autowired
    private OrderExcelService orderExcelService;
    @Autowired
    private OrderAddrService orderAddrService;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private DeliveryFeignClient deliveryFeignClient;
    @Autowired
    private SkuFeignClient skuFeignClient;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private EsOrderFeignClient esOrderFeignClient;
    @Autowired
    private OrderSelfStationService orderSelfStationService;
    @Autowired
    private OrderRefundService orderRefundService;

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);


    /**
     * 分页获取
     */
    @GetMapping("/page")
    public ServerResponseEntity<EsPageVO<EsOrderVO>> page(@ParameterObject OrderSearchDTO orderSearchDTO) {
        orderSearchDTO.setShopId(AuthUserContext.get().getTenantId());
        if(Objects.equals(orderSearchDTO.getStatus(), OrderStatus.PAYED.value())){
            orderSearchDTO.setWaitPurchase(0);
        }
        if(Objects.equals(orderSearchDTO.getStatus(), Constant.WAIT_PURCHASES_STATUS)){
            orderSearchDTO.setStatus(OrderStatus.PAYED.value());
            orderSearchDTO.setWaitPurchase(1);
        }
        //TODO 用户手机号
        if(!Objects.isNull(orderSearchDTO.getPhone())){
            UserApiVO userApiVO=new UserApiVO();
            userApiVO.setPhone(orderSearchDTO.getPhone());
            List<UserApiVO> userList =  userFeignClient.getUserByParam(userApiVO).getData();
            if(userList.size()>0){
                orderSearchDTO.setUserId(userList.get(0).getUserId());
            }
        }
        EsPageVO<EsOrderVO> orderPage = orderService.orderPage(orderSearchDTO);
        List<Long> userIds = new ArrayList<>();
        List<Long> supplierIds = new ArrayList<>();
        List<Long> stationOrderIds = new ArrayList<>();
        for (EsOrderVO esOrderVO : orderPage.getList()) {
            userIds.add(esOrderVO.getUserId());
            supplierIds.add(esOrderVO.getSupplierId());
            if (esOrderVO.getDeliveryType() != null
                    && DeliveryType.STATION.value().equals(esOrderVO.getDeliveryType())) {
                stationOrderIds.add(esOrderVO.getOrderId());
            }
        }

        List<UserApiVO> userList = userFeignClient.getUserByUserIds(userIds).getData();
        Map<Long, String> userMap = userList.stream().collect(Collectors.toMap(UserApiVO::getUserId, UserApiVO::getNickName));
        Map<Long, String> userMap1 = userList.stream().collect(Collectors.toMap(UserApiVO::getUserId, UserApiVO::getPhone));
        List<SupplierApiDetailVO> shopDetailList = supplierDetailFeignClient.listBySupplierIds(supplierIds).getData();
        Map<Long, String> supplierMobileMap = shopDetailList.stream().collect(Collectors.toMap(SupplierApiDetailVO::getSupplierId, SupplierApiDetailVO::getContactPhone));
        // 查找自提订单对应自提人信息
        Map<Long, OrderSelfStationVO> selfStationMap = new HashMap<>(16);
        if (!CollectionUtils.isEmpty(stationOrderIds)) {
            List<OrderSelfStationVO> orderSelfStationVOS = orderSelfStationService.listSelfStationByOrderIds(stationOrderIds);
            selfStationMap = orderSelfStationVOS.stream().collect(Collectors.toMap(OrderSelfStationVO::getOrderId, x -> x));
        }

        // 处理下发货完成时能否修改物流
        for (EsOrderVO esOrderVO : orderPage.getList()) {
            // 补充自提人信息
            OrderSelfStationVO stationVO = selfStationMap.get(esOrderVO.getOrderId());
            if (stationVO != null) {
                esOrderVO.setConsignee(stationVO.getStationUserName());
                esOrderVO.setMobile(stationVO.getStationUserMobile());
            }
            if(!Objects.equals(esOrderVO.getSupplierId(),0L) && supplierMobileMap.containsKey(esOrderVO.getSupplierId())){
                esOrderVO.setSupplierMobile(supplierMobileMap.get(esOrderVO.getSupplierId()));
            }

            esOrderVO.setUserName(null == userMap.get(esOrderVO.getUserId()) ? "*用户已注销*" : userMap.get(esOrderVO.getUserId()));
            esOrderVO.setPhone(userMap1.get(esOrderVO.getUserId()) == null ? null : userMap1.get(esOrderVO.getUserId()));
            esOrderVO.setIsWriteOff(Objects.isNull(userMap.get(esOrderVO.getUserId())));
            // 处理赠品列表
            Map<Long, List<EsOrderItemVO>> giveawayMap = esOrderVO.getOrderItems().stream().filter(orderItemVO -> Objects.equals(orderItemVO.getActivityType(), OrderActivityType.GIVEAWAY.value()))
                    .collect(Collectors.groupingBy(EsOrderItemVO::getActivityId));
            if (MapUtil.isNotEmpty(giveawayMap)) {
                Iterator<EsOrderItemVO> iterator = esOrderVO.getOrderItems().iterator();
                while (iterator.hasNext()) {
                    EsOrderItemVO orderItem = iterator.next();
                    if (Objects.equals(orderItem.getActivityType(), OrderActivityType.GIVEAWAY.value())) {
                        iterator.remove();
                    }
                    orderItem.setGiveawayList(giveawayMap.get(orderItem.getOrderItemId()));
                }
            }

            if (BooleanUtil.isFalse(permission) && StrUtil.isNotBlank(esOrderVO.getMobile())){
                esOrderVO.setMobile(PhoneUtil.hideBetween(esOrderVO.getMobile()).toString());
            }
            if (!Objects.equals(esOrderVO.getStatus(), OrderStatus.CONSIGNMENT.value()) ||
                    !Objects.equals(esOrderVO.getDeliveryType(), DeliveryType.DELIVERY.value())) {
                continue;
            }
            int updateOrViewDeliveryInfo = 0;
            for (EsOrderItemVO orderItem : esOrderVO.getOrderItems()) {
                if (Objects.nonNull(orderItem.getDeliveryType()) && Objects.equals(orderItem.getDeliveryType(), DeliveryType.DELIVERY.value())) {
                    updateOrViewDeliveryInfo = 1;
                    break;
                }
            }
            esOrderVO.setUpdateOrViewDeliveryInfo(updateOrViewDeliveryInfo);
        }
        return ServerResponseEntity.success(orderPage);
    }

    /**
     * 获取信息
     */
    @GetMapping("/order_info/{orderId}")
    public ServerResponseEntity<OrderVO> info(@ParameterObject @PathVariable("orderId") Long orderId) throws UnsupportedEncodingException {
        // 订单和订单项
        Order order = orderService.getOrderAndOrderItemData(orderId, AuthUserContext.get().getTenantId());
        logger.info("获取订单和订单项信息：{}", order.toString());
        // 详情用户收货地址
        OrderAddr orderAddr = orderAddrService.getById(order.getOrderAddrId());
        order.setOrderAddr(mapperFacade.map(orderAddr, OrderAddr.class));
        OrderVO orderVO = mapperFacade.map(order, OrderVO.class);
        orderService.getReturnOrderStatus(orderVO);
        // 处理下赠品
        //List<OrderItemVO> orderItemDbList = orderItemService.listOrderItemAndLangByOrderId(orderId);
        // 获取赠品map
        Map<Long, List<OrderItemVO>> giveawayMap = orderVO.getOrderItems().stream().filter(item -> Objects.equals(item.getActivityType(), OrderActivityType.GIVEAWAY.value()))
                .collect(Collectors.groupingBy(OrderItemVO::getActivityId));
        List<OrderItemVO> orderItemDbList = new ArrayList<>();
        for (OrderItemVO orderItem : orderVO.getOrderItems()) {
            // 赠品订单项不需要进行处理
            if(Objects.equals(orderItem.getActivityType(), OrderActivityType.GIVEAWAY.value())){
                continue;
            }
            // 放入赠品
            if(giveawayMap.containsKey(orderItem.getOrderItemId())){
                orderItem.setGiveawayList(giveawayMap.get(orderItem.getOrderItemId()));
            }
            orderItemDbList.add(orderItem);
        }
        orderVO.setOrderItems(orderItemDbList);
        logger.info("获取订单和订单项vo信息：{}", orderVO.toString());
        // 补充自提点信息
        if (order.getDeliveryType() != null
                && DeliveryType.STATION.value().equals(order.getDeliveryType())) {
            OrderSelfStationVO stationVO = orderSelfStationService.getStationByOrderId(orderId);
            logger.info("获取自提点信息stationVO:{}", stationVO);
            orderVO.setOrderSelfStationVO(stationVO);
        }
         // 补充供应商信息
        Long supplierId = order.getSupplierId();
        if(supplierId == null || supplierId == 0L) {
            List<Long> supplierIds = new ArrayList<>();
            List<Long> spuIds = orderItemDbList.stream().map(OrderItemVO::getSpuId).collect(Collectors.toList());
            List<SpuVO> spuVOList = productFeignClient.listSpuBySpuIds(spuIds).getData();
            if (!CollectionUtils.isEmpty(spuVOList)) {
                supplierIds = spuVOList.stream().map(SpuVO::getSupplierId).filter(Objects::nonNull).collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(supplierIds)) {
                // 商品默认的供应商id是-1
                supplierId = supplierIds.get(0);
            }
        }
        if (supplierId != null
                && supplierId != 0L && supplierId != -1L) {
            SupplierDetailBO supplierDetailBO = supplierDetailFeignClient.getSupplierBySupplierId(supplierId).getData();
            logger.info("获取供应商信息supplierDetailBO:{}", supplierDetailBO);
            if (supplierDetailBO != null) {
                orderVO.setSupplierId(supplierDetailBO.getSupplierId());
                orderVO.setSupplierName(supplierDetailBO.getSupplierName());
                orderVO.setSupplierMobile(supplierDetailBO.getContactPhone());
            }
        }
        // 预售订单获取预售信息
        if(Objects.nonNull(order.getPreSaleType()) && !Objects.equals(order.getPreSaleType(), PreSaleType.DISABLE.value())){
            OrderPreSaleInfoVO orderPreSaleInfo = orderPreSaleInfoService.getByOrderId(order.getOrderId());
            logger.info("获取预售信息orderPreSaleInfo:{}", orderPreSaleInfo);
            orderVO.setPayTime(orderPreSaleInfo.getBalancePayTime());
            orderVO.setOrderPreSaleInfoVO(orderPreSaleInfo);
        }
        //套餐优惠金额
        for (OrderItemVO orderItem : orderVO.getOrderItems()) {
            if (Objects.isNull(orderItem.getComboAmount())){
                continue;
            }
            orderItem.setShareReduce(orderItem.getShareReduce() + orderItem.getComboAmount());
        }
        return ServerResponseEntity.success(orderVO);
    }

    /**
     * 获取订单用户下单地址
     */
    @GetMapping("/order_addr/{orderAddrId}")
    public ServerResponseEntity<OrderAddrVO> getOrderAddr(@ParameterObject @PathVariable("orderAddrId") Long orderAddrId) {
        OrderAddr orderAddr = orderAddrService.getById(orderAddrId);
        return ServerResponseEntity.success(mapperFacade.map(orderAddr, OrderAddrVO.class));
    }

    /**
     * 订单项待发货数量查询
     */
    @GetMapping("/order_item_and_address/{orderId}")
    public ServerResponseEntity<OrderVO> getOrderItemAndAddress(@ParameterObject @PathVariable("orderId") Long orderId) {
        // 订单和订单项
        Order order = orderService.getOrderAndOrderItemData(orderId, AuthUserContext.get().getTenantId());
        OrderVO orderVO = mapperFacade.map(order, OrderVO.class);
        List<OrderItemVO> orderItems = orderVO.getOrderItems();
        for (OrderItemVO orderItem : orderItems) {
            orderItem.setChangeNum(orderItem.getBeDeliveredNum() == -1 ? orderItem.getCount() : orderItem.getBeDeliveredNum());
        }
        // 用户收货地址
        OrderAddr orderAddr = orderAddrService.getById(order.getOrderAddrId());
        orderVO.setOrderAddr(mapperFacade.map(orderAddr, OrderAddrVO.class));
        return ServerResponseEntity.success(orderVO);
    }

    /**
     * 发货
     */
    @PostMapping("/delivery")
    public ServerResponseEntity<Void> delivery(@Valid @RequestBody DeliveryOrderDTO deliveryOrderParam)
    {
        // TODO 检查发货数量
        Order order = orderService.getOrderAndOrderItemData(deliveryOrderParam.getOrderId(), AuthUserContext.get().getTenantId());
        logger.info("获取订单信息order:{}", order);
        if (Objects.isNull(order)) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        // 订单不在支付状态
        if (!Objects.equals(order.getStatus(), OrderStatus.PAYED.value())) {
            return ServerResponseEntity.showFailMsg("订单状态异常");
        }
        List<DeliveryOrderItemDTO> selectOrderItems = deliveryOrderParam.getSelectOrderItems();
        if(CollectionUtil.isEmpty(selectOrderItems)){
            return ServerResponseEntity.showFailMsg("请至少选择一个订单项进行发货操作");
        }
        Map<Long, OrderItem> orderItemMap = order.getOrderItems().stream().collect(Collectors.toMap(OrderItem::getOrderItemId, orderItem -> orderItem));
        for (DeliveryOrderItemDTO selectOrderItem : selectOrderItems) {
            if(!orderItemMap.containsKey(selectOrderItem.getOrderItemId())){
                throw new LuckException("订单项不存在");
            }
            OrderItem orderItem = orderItemMap.get(selectOrderItem.getOrderItemId());
            if(orderItem.getBeDeliveredNum() < selectOrderItem.getChangeNum()){
                throw new LuckException("订单项可发货数量不足,请刷新后重试");
            }
        }
        List<OrderRefundVO> orderRefunds = orderRefundService.getProcessingOrderRefundByOrderId(order.getOrderId());
        // 移除退款成功的退款记录
        orderRefunds.removeIf(orderRefund -> Objects.equals(orderRefund.getReturnMoneySts(), ReturnProcessStatusEnum.SUCCESS.value()));
        if (CollectionUtil.isNotEmpty(orderRefunds)) {
            throw new LuckException("该订单有退款信息正在处理当中，请处理完毕之后再进行发货的操作!");
        }
        orderService.delivery(deliveryOrderParam);
        esOrderFeignClient.updateOrder(deliveryOrderParam.getOrderId());
        return ServerResponseEntity.success();
    }

    /**
     * 采购订单
     */
    @PutMapping("/sourcing_order")
    public ServerResponseEntity<Void> sourcingOrder(@Valid @RequestBody OrderAdminDTO orderDTO) {
        Order order = orderService.getOrderAndOrderItemData(orderDTO.getOrderId(), AuthUserContext.get().getTenantId());
        if (Objects.isNull(order)) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        // 订单不在支付状态
        if (!Objects.equals(order.getStatus(), OrderStatus.PAYED.value())) {
            return ServerResponseEntity.showFailMsg("订单状态异常");
        }
        boolean hasRefund =  !Objects.isNull(order.getRefundStatus())
                && !Objects.equals(order.getRefundStatus(), RefundStatusEnum.DISAGREE.value())
                && !Objects.equals(order.getRefundStatus(), RefundStatusEnum.PARTIAL_SUCCESS.value());
        // 订单退款中，不能进行采购操作
        if (hasRefund) {
            return ServerResponseEntity.showFailMsg("订单退款中，不能进行采购操作");
        }
        // 检查商家结算金额是否足够
        ServerResponseEntity<Long> amountResp = shopWalletFeignClient.getSettlementAmountByShopId(order.getShopId());
        if(!amountResp.isSuccess()){
            logger.info("获取商家结算金额失败，msg:{}", amountResp.getMsg());
            throw new LuckException(amountResp.getMsg());
        }
        if(amountResp.getData() < order.getPurchaseSpreadAmount()){
            return ServerResponseEntity.showFailMsg("商家余额不足，请充值！");
        }
        // 执行金额扣除
        orderService.sourcingOrder(order);
        return ServerResponseEntity.success();
    }

    /**
     * 修改订单金额
     */
    @PutMapping("/change_amount")
    public ServerResponseEntity<Void> changeAmount(@RequestBody OrderAdminDTO orderAdminDTO) {
        Long minFreightAmount = 0L;
        if (Objects.isNull(orderAdminDTO.getFreightAmount())) {
            orderAdminDTO.setFreightAmount(minFreightAmount);
        } else if (orderAdminDTO.getFreightAmount() < minFreightAmount) {
            throw new LuckException("运费不能小于零");
        }
        Order dbOrder = orderService.getOrderAndOrderItemData(orderAdminDTO.getOrderId(), AuthUserContext.get().getTenantId());
        if(Objects.equals(dbOrder.getPreSaleType(), PreSaleType.DEPOSIT.value())){
            logger.info("修改预售订单金额");
            orderService.changeAmountByPreSale(orderAdminDTO, dbOrder);
        }else{
            logger.info("修改普通订单金额");
            orderService.changeAmount(orderAdminDTO, dbOrder);
        }
        esOrderFeignClient.updateOrder(orderAdminDTO.getOrderId());
        return ServerResponseEntity.success();
    }

    @GetMapping("/get_change_amount")
    @Operation(summary = "查询修改订单地址后的运费")
    public ServerResponseEntity<Double> getChangeAmount(@ParameterObject OrderChangeAddrDTO param) {
        Order dbOrder = orderService.getOrderAndOrderItemData(param.getOrderId(), AuthUserContext.get().getTenantId());
        if (dbOrder.getStatus() > OrderStatus.PAYED.value() && !Objects.equals(dbOrder.getStatus(), OrderStatus.WAIT_GROUP.value())) {
            throw new LuckException("订单状态异常，无法更改订单地址");
        }
        List<OrderItem> orderItems = orderItemService.listOrderItemsByOrderId(dbOrder.getOrderId());
        List<Long> skuIds = orderItems.stream().map(OrderItem::getSkuId).collect(Collectors.toList());
        ServerResponseEntity<List<SkuAddrVO>> responseEntity = skuFeignClient.listSpuDetailByIds(skuIds);
        if (responseEntity.isFail()) {
            throw new LuckException(responseEntity.getMsg());
        }
        List<SkuAddrVO> skuList = responseEntity.getData();
        Map<Long, SkuAddrVO> skuMap = skuList.stream().collect(Collectors.toMap(SkuAddrVO::getSkuId, s -> s));
        List<ShopCartItemVO> shopCartItems = new ArrayList<>();
        for (OrderItem orderItem : dbOrder.getOrderItems()) {
            //如果是赠品则不需要处理运费
            if(Objects.equals(orderItem.getActivityType(), OrderActivityType.GIVEAWAY.value())){
                continue;
            }
            SkuAddrVO sku = skuMap.get(orderItem.getSkuId());
            ShopCartItemVO shopCartItem = new ShopCartItemVO();
            shopCartItem.setSkuId(orderItem.getSkuId());
            shopCartItem.setCount(orderItem.getCount());
            shopCartItem.setTotalAmount(orderItem.getSpuTotalAmount());
            shopCartItem.setShopId(orderItem.getShopId());
            shopCartItem.setVolume(sku.getVolume());
            shopCartItem.setWeight(sku.getWeight());
            shopCartItem.setDeliveryTemplateId(sku.getDeliveryTemplateId());
            shopCartItems.add(shopCartItem);
        }
        UserAddrVO userAddrVO = new UserAddrVO();
        userAddrVO.setAreaId(param.getAreaId());
        if (Objects.equals(dbOrder.getDeliveryType(), DeliveryType.SAME_CITY.value())) {
            userAddrVO.setLng(param.getLng());
            userAddrVO.setLat(param.getLat());
        }
        ChangeOrderAddrDTO changeOrderAddrDTO = new ChangeOrderAddrDTO(shopCartItems, dbOrder.getFreightAmount(), userAddrVO, dbOrder.getDeliveryType());
        ServerResponseEntity<Double> changeResponse = deliveryFeignClient.getOrderChangeAddrAmount(changeOrderAddrDTO);
        if (changeResponse.isFail()) {
            throw new LuckException(changeResponse.getMsg());
        }
        return ServerResponseEntity.success(changeResponse.getData());
    }

    /**
     * 修改用户订单地址
     * @return 是否修改成功
     */
    @PutMapping("/change_user_addr")
    public ServerResponseEntity<Void> changeUserAddr(@RequestBody @Valid OrderAddrDTO orderAddrDTO) {
        Order orderDb = orderService.getByOrderId(orderAddrDTO.getOrderId());
        if (orderDb.getStatus() <= OrderStatus.PAYED.value() || Objects.equals(orderDb.getStatus(), OrderStatus.WAIT_GROUP.value())) {
            logger.info("修改订单地址");
            OrderAddr orderAddr = mapperFacade.map(orderAddrDTO, OrderAddr.class);
            orderAddrService.update(orderAddr);
        } else {
            throw new LuckException("订单状态异常，无法更改订单地址");
        }
        return ServerResponseEntity.success();
    }

    /**
     * 修改订单备注
     *
     * @param order
     * @return 是否修改成功
     */
    @PutMapping("/change_order_remark")
    public ServerResponseEntity<Void> changeOrderRemark(@RequestBody @Valid Order order) {
        Order orderDb = orderService.getByOrderId(order.getOrderId());
        orderDb.setShopRemarks(order.getShopRemarks());
        orderService.update(orderDb);
        return ServerResponseEntity.success();
    }

    @GetMapping("/sold_excel")
    @Operation(summary = "导出excel" , description = "导出订单excel")
    public ServerResponseEntity<Void> orderSoldExcel(HttpServletResponse response, @ParameterObject OrderSearchDTO orderSearchDTO) {
        orderSearchDTO.setShopId(AuthUserContext.get().getTenantId());
        if(Objects.equals(orderSearchDTO.getStatus(), Constant.WAIT_PURCHASES_STATUS)){
            logger.info("导出待采购订单excel");
            orderSearchDTO.setStatus(OrderStatus.PAYED.value());
            orderSearchDTO.setWaitPurchase(1);
        }
        List<OrderExcelVO> list = orderExcelService.excelOrderList(orderSearchDTO);
        ExcelUtil.soleExcel(response, list, OrderExcelVO.EXCEL_NAME, OrderExcelVO.MERGE_ROW_INDEX, OrderExcelVO.MERGE_COLUMN_INDEX, OrderExcelVO.class);
        return ServerResponseEntity.success();
    }

    @GetMapping("/un_delivery_sold_excel")
    @Operation(summary = "导出待发货的订单excel")
    public ServerResponseEntity<Void> unDeliveryOrderSoldExcel(HttpServletResponse response, @ParameterObject OrderSearchDTO orderSearchDTO) {
        orderSearchDTO.setShopId(AuthUserContext.get().getTenantId());
        orderSearchDTO.setSupplierDeliveryType(SupplierDeliveryType.SHOP_DELIVERY.value());
        orderSearchDTO.setStatus(OrderStatus.PAYED.value());
        // 只查询快递发货的订单
        orderSearchDTO.setDeliveryType(DeliveryType.DELIVERY.value());
        orderExcelService.excelUnDeliveryOrderList(response, orderSearchDTO);
        return ServerResponseEntity.success();
    }

    @PostMapping("/export_order_excel")
    @Operation(summary = "导入订单")
    public ServerResponseEntity<String> exportOrderExcel(@RequestParam("excelFile") MultipartFile file) {
        if (Objects.isNull(file)) {
            throw new LuckException("网络繁忙，请稍后重试");
        }
        String info = null;
        try {
            Map<Integer, List<String>> errorMap = new HashMap<>(8);
            EasyExcel.read(file.getInputStream(), UnDeliveryOrderExcelVO.class, new OrderExcelListener(orderExcelService, errorMap)).sheet().doRead();
            info = orderExcelService.orderExportError(errorMap);
        } catch (IOException e) {
            throw new LuckException(e.getMessage());
        }
        return ServerResponseEntity.success(info);
    }

    @GetMapping("/get_shop_order_by_userId")
    @Operation(summary = "分页获取某个用户的订单数据", description = "分页获取某个用户的订单数据")
    public ServerResponseEntity<EsPageVO<EsOrderVO>> getShopOrderByUserId(PageDTO pageDTO, @ParameterObject String userId){
        EsPageVO<EsOrderVO> pages = orderService.pageByUserId(pageDTO,userId);
        return ServerResponseEntity.success(pages);
    }
}
